#include "lex.h"
#include <math.h>
#include <string.h>
using namespace std;

char * alphabet = "abcdefghijklmnopqrstuvwxyz";

string reverse(string x) {
	string result;
	for(int i = x.size()-1; i >= 0; i--)
		result.push_back(x[i]);
	return result;
}

int atodigit(char a) {
	return a - 'a';
}

string enbase(int x) {
	int n = 26;
	string s;
	if(x < n) {
		s.push_back(alphabet[x]);
		return s;
	}
	s = enbase(x/n);
	s.push_back(alphabet[x%n]);
	return s;
}

int debase(string x) {
	int n = 26;
	int result = 0;
	string revx = reverse(x);
	for(int i = 0; i < revx.size(); i++) {
		result += atodigit(revx[i]) * pow(n, i);
	}
	return result;
}

/*
def split(a, b, n):
        x = debase(a)
        y = debase(b)
        s = (x + y) / n
        t = []
        i = 1
        t.append(a)
        while i < n :
                t.append(enbase(i*s))
                i += 1
        t.append(b)
        return t


*/

vector<string> lex_divide(const char * x, const char * y, int len, int n) {
	vector<string> parts;
	int str1 = debase(string(x));
	int str2 = debase(string(y));
	int incr = (str1 + str2) / n;
	parts.push_back(string(x));
	for(int i = 1; i < n; i++) {
		parts.push_back(enbase(i*incr));
	}
	parts.push_back(string(y));
	return parts;
}

char digit_to_char(unsigned char d) {
	if(d >= 0 && d <= 9)
		return d + '0';
	else
		return (d - 10) + 'a';
}

char * hash_to_str(unsigned char* hash) {
	char * str = new char[41];
	memset(str, 0, 41);
	for(int i = 0; i < 20; i++) {
		str[i*2] = digit_to_char(hash[i] >> 4 & 0x0f);
		str[(i*2)+1] = digit_to_char(hash[i] & 0x0f);
	}
	return str;
}
